package com.oracle.controller;

import com.aliyuncs.utils.StringUtils;
import com.oracle.service.impl.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin //跨域支持
public class SmsApiController {

    @Resource(name = "sendSmsImpl")
    private SendSms sendSmsImpl;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{phone}")
    public String code(@PathVariable("phone") String phone){
        // 调用方法发送（模拟真实的业务）使用redis
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return phone + ":" +code + "已存在，还没有过期";
        }

        //生产验证码并存储到redis中
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String,Object> param = new HashMap<>();
        param.put("code",code);

        boolean isSend = sendSmsImpl.send(phone, null, param);

        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.SECONDS);
            return phone + ":" +code + "发送成功！";
        }else{
            return "发送失败!";
        }
    }
}
